package com.routing;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

/**
 * java -cp $CP EmitLogDirect error "Run. Run. Or it will explode."
 *
 * 路由：依据消息中的routingKey与binding Key的匹配情况来分发消息
 */
public class EmitLogDirect {

    private static final String EXCHANGE_NAME = "direct_logs";


    //java -cp $CP EmitLogDirect error "Run. Run. Or it will explode."
    public static void main(String[] argv) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        try (Connection connection = factory.newConnection();
             Channel channel = connection.createChannel()) {
            //Direct类型的交换机，消息中的routingKey与绑定中的bindingKey完全一样就把消息发给对应的队列
            channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.DIRECT);

            String severity = getSeverity(argv);
            String message = getMessage(argv);

            channel.basicPublish(EXCHANGE_NAME, severity, null, message.getBytes("UTF-8"));
            System.out.println(" [x] Sent '" + severity + "':'" + message + "'");
        }
    }

// info abc 或者 error def
    private static String getSeverity(String[] strings) {
        if (strings.length < 1)
            return "info";
        return strings[0];
    }
// error helloworld
    private static String getMessage(String[] strings) {
        if (strings.length < 2)
            return "Hello World!";
        return strings[1];
        //复杂了点，可以简化为只有2个参数，第一个参数表示严重程度（给getServerity方法用），
        // 第二个参数表示消息，这里返回这个消息即可
        //return joinStrings(strings, " ", 1);
    }


}